package com.njtoyo.taxi.admin.config.mongo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * @author Dell
 * @date 2021-05-28 22:40
 */
@Configuration
public class MultipleMongoConfig {

    @Autowired
    private MultipleMongoProperties mongoProperties;

    @Autowired
    private MongoMappingContext mongoMappingContextPrimary;

    @Autowired
    private MongoMappingContext mongoMappingContextSecond;

    @Primary
    @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate primaryMongoTemplate() {
        return new MongoTemplate(primaryFactory());
    }

    @Bean
    @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate secondaryMongoTemplate() {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(secondaryFactory());
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContextSecond);

        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return new MongoTemplate(secondaryFactory(), converter);
    }

    @Primary
    public MongoDatabaseFactory primaryFactory() {
        return new SimpleMongoClientDatabaseFactory(mongoProperties.getPrimary().getUri());
    }

    @Bean
    public MongoDatabaseFactory secondaryFactory() {
        return new SimpleMongoClientDatabaseFactory(mongoProperties.getSecondary().getUri());
    }


}
